const $login = require('../index')
import memberState from '@src/store/member'
import base from '@src/store/base'
import {weAtob}  from '../../../common/weapp-jwt'
import {
	storeBindingsBehavior
} from 'mobx-miniprogram-bindings'

Component({
  behaviors: [storeBindingsBehavior],
  storeBindings:[
    {
      store: base,
      fields: ['protocol']
    }
  ],
  properties: {
    auto: {
      type: Boolean,
      value: true
    },
    checkMember: {
      type: Boolean,
      value: true
    },
  },
  data: {
    hasLogin: false,
    isAnonUser: false,
    waitBack: false,
    showDialog: false,
    context: ''
  },
  pageLifetimes: {
    show: function () {
      if (this.data.waitBack) {
        // 授权回调
        this.setData({ waitBack: false })
        if (!$login.isLogin()) {
          // 授权异常提醒
          wx.showModal({
            title: "提示", content: "为了您的正常使用，请您先进行授权登录",
            showCancel: true,
            success: sm => {
              if (sm.confirm) {
                this.setData({showDialog:true})
              }
            }
          });
          return;
        }
      }
      // 避免回调比状态器快
      wx.nextTick(() => {
        this._check();
      })
    },
  },
  observers: {
    'protocol'(data) {
      if(!data) return
      const { content } = data 
      var context = decodeURI(weAtob(content))
      this.setData({context})
      
    }
  },
  methods: {
    loginChange(e) {
      const { isagree } = e.currentTarget.dataset
      const appOps = wx.getEnterOptionsSync()
      !isagree && appOps.scene === 1037 && wx.navigateBackMiniProgram()
      this.setData({showDialog:false});
      if(!isagree) return
      this._login(true)
    },
    requireLogin() {
      return new Promise((resolve, reject) => {
        // 弹窗 登录询问
        if (this.data.hasLogin) {
          resolve()
        } else {
          this.setData({
            showDialog: true
          })
        }
      })
    },
    isLogin() {
      return this.data.hasLogin;
    },
    isAnonUser() {
      return this.data.isAnonUser;
    },
    // 内部函数
    _check() {
      //是否有token已登录
      const hasTokenLogin = $login.isLogin();
      //是否是游客
      const isAnonUser = $login.isAnonUser();
      //已经登录可以正常进入请求base接口了
      if (!this.data.hasLogin && hasTokenLogin) {
        this._onLogin();
        return;
      }
      if (this.data.hasLogin && hasTokenLogin) {
        return;
      }
      if (this.data.hasLogin && !hasTokenLogin) {
        this._onLogout();
        return;
      }
      if (this.data.auto || !isAnonUser) {
        // 登录
        this._login(this.data.auto)
      }
      if (isAnonUser && !this.data.isAnonUser) {
        this._onAnon();
      }
    },
    _login(force = true) {
      console.info("发起微信登录")
      wx.login({
        success: (res) => {
          if (res.code) {
            $login.loginApi({
              code: res.code,
              webviewAuth: force,
              scope: 0
            }).then((resp) => {
              res = resp.data
              console.log('reslogin', res)
              if (res.code === 0) {
                $login.setToken(res.data.token, res.data.expireTime);
                $login.setAnon(res.data.anonUser, res.data.expireTime);
                if (!res.data.anonUser) {
                  this._onLogin();
                } else {
                  this._onAnon();
                }
              } else if (res.code === 61000) {
                this.setData({ waitBack: true })
                wx.navigateTo({
                  url: $login.webviewPath + `?loginParams=${JSON.stringify({ 'webViewUrl': encodeURIComponent(res.data.url) })}`
                });
              } else {
                wx.showToast({
                  title: res.msg,
                  icon: 'none',
                  duration: 5000
                });
              }
            }).catch((error) => {
              console.error(error)
              wx.showToast({
                title: error,
                icon: 'none',
                duration: 5000
              });
            })
          } else {
            wx.showToast({
              title: "网络异常",
              icon: 'none',
              duration: 5000
            });
          }
        }
      })
    },
    _onAnon() {
      this.setData({
        "isAnonUser": true
      });
      console.info("_onAnon")
      this.triggerEvent('anon', {})
    },
    _onLogin() {
      if (this.data.checkMember) {
        memberState.initBase().then(res => {
          this.setData({ "hasLogin": true });
          this.triggerEvent('login', {})
        });
      } else {
        this.setData({
          "hasLogin": true
        });
        this.triggerEvent('login', {})
      }
    },
    _onLogout() {
      this.setData({ "hasLogin": false });
      this.setData({
        "isAnonUser": false
      });
      this.triggerEvent('logout', {})
    }
  }
})
